"use strict";
import { useState, useEffect, forwardRef, useImperativeHandle } from "react";
import { Form, Input, Select, DatePicker, Checkbox, Button, Space } from "antd";
import moment from "moment";
import PropTypes from "prop-types";
/*
 * 组件注释
 * create by wuqiong
 * creation time 2021/05/19
 * 水平布局 简易的sreach 组件
 * */
const datesOption = ["date", "rangePicker"];
const checkboxsOption = ["checkbox"];
const { Option } = Select;
const { RangePicker } = DatePicker;

const getConf = (dataSource, option) =>
  dataSource.filter(item => option.includes(item.type)) || [];

const PickerFormat = {
  year: "YYYY",
  month: "YYYY-MM",
  quarter: "YYYY-Q",
  week: "YYYY-W",
};
const Index = forwardRef((props, ref) => {
  const { onFinish, dataSource, btnText, isReset, automatic, ...otherProp } =
    props;
  const [dates, setDates] = useState(getConf(dataSource, datesOption));
  const [checkboxs, setCheckboxs] = useState(
    getConf(dataSource, checkboxsOption)
  );
  const [form] = Form.useForm();

  const getFormItemHtml = data => {
    const {
      name,
      label,
      placeholder,
      type = "input",
      option,
      width = 180,
      text,
      element,
      fieldNames,
      ...other
    } = data;

    const formItemHtml = type => {
      switch (type) {
        case "select":
          return (
            <Select
              style={{ width }}
              allowClear
              placeholder={
                placeholder
                  ? placeholder
                  : label
                  ? `请选择${label}`
                  : "请选择..."
              }
              dropdownMatchSelectWidth={false}
              {...other}>
              {option.map(child => (
                <Option
                  value={child[fieldNames?.value] || child.key}
                  key={child[fieldNames?.value] || child.key}>
                  {child[fieldNames?.label] || child.value}
                </Option>
              ))}
            </Select>
          );

        case "date":
          return (
            <DatePicker
              style={{ width, borderRadius: 5 }}
              allowClear
              {...other}
              placeholder={
                placeholder
                  ? placeholder
                  : label
                  ? `请选择${label}`
                  : "请选择时间..."
              }
            />
          );

        case "rangePicker":
          const _placeholder =
            Array.isArray(placeholder) && placeholder.length
              ? placeholder
              : ["开始时间", "结束时间"];

          return (
            <RangePicker
              style={{ width, borderRadius: 5 }}
              allowClear
              placeholder={_placeholder}
              {...other}
            />
          );
        case "checkbox":
          return <Checkbox>{text}</Checkbox>;

        default:
          return (
            <Input
              allowClear
              {...other}
              style={{ width, borderRadius: 5 }}
              placeholder={
                placeholder
                  ? placeholder
                  : label
                  ? `请输入${label}`
                  : "请输入..."
              }
            />
          );
      }
    };

    return (
      <Form.Item
        style={{ marginRight: name === dataSource?.at(-1)?.name ? 0 : "10px" }}
        key={name}
        name={name}
        label={label}
        {...(type === "checkbox" ? { valuePropName: "checked" } : {})}>
        {element ?? formItemHtml(type)}
      </Form.Item>
    );
  };

  const _onFinish = values => {
    let newVals = {};
    for (let key in values) {
      newVals[key] = window.isEmpty(values[key]) ? undefined : values[key];
    }
    if (dates.length) {
      dates.forEach(item => {
        if (newVals[item.name]) {
          let timeDate = null;
          let defaultFormat = "YYYY-MM-DD";
          if (item.picker) {
            defaultFormat = PickerFormat[item.picker];
          }

          let format = item.format || defaultFormat;

          if (item.notUseFormat) {
            format = defaultFormat;
          }

          if (item.type === "rangePicker") {
            timeDate = newVals[item.name].map(child => {
              return child ? moment(child).format(format) : "";
            });
          } else {
            timeDate = moment(newVals[item.name]).format(format);
          }

          newVals = {
            ...newVals,
            [item.name]: timeDate,
          };
        }
      });
    }
    if (checkboxs.length) {
      checkboxs.forEach(item => {
        newVals = {
          ...newVals,
          [item.name]: Number(newVals[item.name]) || undefined,
        };
      });
    }
    onFinish(newVals);
  };

  const reset = () => {
    form.resetFields();
    _onFinish({});
  };
  const onFieldsChange = () => {
    if (!automatic) return;
    const values = form.getFieldsValue();
    _onFinish(values);
  };
  useEffect(() => {
    setDates(getConf(dataSource, datesOption));
    setCheckboxs(getConf(dataSource, checkboxsOption));
  }, [dataSource]);

  useImperativeHandle(ref, () => ({ ...form }));

  return (
    <div className={"searchForm"}>
      <Form
        form={form}
        name="search"
        layout="inline"
        onFinish={_onFinish}
        onFieldsChange={onFieldsChange}
        {...otherProp}>
        {dataSource.map(item => getFormItemHtml(item))}
        <Form.Item style={{ marginRight: 0 }}>
          <Space>
            {!automatic ? (
              <Button type="primary" htmlType="submit">
                {btnText}
              </Button>
            ) : null}
            {isReset ? (
              <Button type="primary" onClick={() => reset()}>
                重置
              </Button>
            ) : null}
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
});
export default Index;
Index.defaultProps = {
  isReset: false, //重置按钮
  automatic: false, //自动提交
  onFinish: values => console.log(values),
  dataSource: [
    {
      label: "label",
      name: "select",
      placeholder: "placeholder",
      type: "select", // input
      option: [
        {
          key: "key",
          value: "value",
        },
      ],
    },
    {
      label: "label",
      name: "time",
      placeholder: "placeholder",
      type: "date",
      picker: "year",
      format: "YYYY-MM-DD",
    },
    {
      text: "label",
      name: "checkbox",
      type: "checkbox",
      // element:  element可以传入组件自定义功能
    },
  ],
  btnText: "查询",
};
Index.propTypes = {
  dataSource: PropTypes.array,
  onFinish: PropTypes.func,
  btnText: PropTypes.string,
};
